#!/bin/bash

echo "=========================================="
echo "  Seata 分布式事务功能测试"
echo "=========================================="
echo ""

# 健康检查
echo "【1】健康检查"
echo "Order Service:"
curl -s http://localhost:8001/order/health
echo ""
echo "Storage Service:"
curl -s http://localhost:8002/storage/health  
echo ""
echo "Account Service:"
curl -s http://localhost:8003/account/health
echo ""
echo ""

# AT 模式测试
echo "【2】AT 模式 - 分布式事务测试"
echo "创建订单：用户1 购买 iPhone 15 Pro 1个，金额 10 元"
curl -X POST http://localhost:8001/order/create/at \
  -H "Content-Type: application/json" \
  -d '{"userId":1,"productId":1,"count":1,"money":10.00}'
echo ""
echo ""

sleep 2

# TCC 模式测试
echo "【3】TCC 模式 - 分布式事务测试"
echo "创建订单：用户2 购买 MacBook Pro 1个，金额 20 元"
curl -X POST http://localhost:8001/order/create/tcc \
  -H "Content-Type: application/json" \
  -d '{"userId":2,"productId":2,"count":1,"money":20.00}'
echo ""
echo ""

sleep 2

# 查看数据
echo "【4】查看数据库数据"
echo ""
echo "最新订单（最近3条）："
docker exec springcloud-mysql mysql -uroot -proot123456 seata_order \
  -e "SELECT id, user_id, product_id, count, money, status FROM tb_order ORDER BY id DESC LIMIT 3;" 2>/dev/null | tail -n +2

echo ""
echo "库存状态："
docker exec springcloud-mysql mysql -uroot -proot123456 seata_storage \
  -e "SELECT product_id, product_name, used, residue, frozen FROM tb_storage;" 2>/dev/null | tail -n +2

echo ""
echo "账户状态："
docker exec springcloud-mysql mysql -uroot -proot123456 seata_account \
  -e "SELECT user_id, user_name, used, residue, frozen FROM tb_account;" 2>/dev/null | tail -n +2

echo ""
echo "=========================================="
echo "  ✅ Seata 功能测试完成！"
echo "=========================================="
echo ""
echo "说明："
echo "  - AT 模式：自动管理分布式事务，无需编写补偿代码"
echo "  - TCC 模式：手动管理事务，使用 frozen 字段冻结资源"
echo ""
echo "下一步："
echo "  - 运行回滚测试：./scripts/05-回滚测试.sh"
echo "  - 查看 Seata 日志：docker logs -f springcloud-seata"
